package com.yeyaomai.dksns.flowis.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
import org.springframework.util.ReflectionUtils.FieldFilter;

/**
 * 
 * @author dingtao@yeyaomai.net
 * 
 * @param <T>
 */
public class ListPropertyAndValueTool {


	public static <T> List<String> display(final T t,
			final List<String> fieldNames) {

		final List<String> result = new ArrayList<String>();

		ReflectionUtils.doWithFields(t.getClass(), new FieldCallback() {

			@Override
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {

				ReflectionUtils.makeAccessible(field);

				Object obj = ReflectionUtils.getField(field, t);
				// TODO if(obj.getClass().isArray() ,obj instanceof List obj
				// instanceof Set obj instanceof Map) 简单处理下
				if (obj == null) {
					result.add("---");
				} else {
					result.add(obj.toString());
				}

			}
		}, new FieldFilter() {
			@Override
			public boolean matches(Field field) {

				if (fieldNames != null && fieldNames.contains(field.getName())) {
					return true;
				}
				return false;
			}
		});

		return result;
	}

	/**
	 * 
	 * @param query
	 *            mongodb 查询对象
	 * @param order
	 *            请求查询表单
	 * @param document
	 *            mongodb 文档对象
	 * @param exincludeField
	 *            排除的属性
	 */
	public static <T, V> void querySaveCriteria(final Query query,
			final T order, final Class<V> document,
			final List<String> includeField) {

		ReflectionUtils.doWithFields(order.getClass(), new FieldCallback() {
			@Override
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {

				ReflectionUtils.makeAccessible(field);
				Object obj = ReflectionUtils.getField(field, order);
				if (obj == null) {
					return;
				}
				// TODO if(obj.getClass().isArray() ,obj instanceof List obj
				// instanceof Set obj instanceof Map)
				if (obj instanceof String && StringUtils.isEmpty((String) obj)) {
					return;
				}

				query.addCriteria(new Criteria(field.getName()).is(obj));

			}
		}, new FieldFilter() {
			@Override
			public boolean matches(Field field) {

				if (CollectionUtils.containsInstance(includeField,
						field.getName())
						&& null != ReflectionUtils.findField(document,
								field.getName())) {
					return true;
				}
				return false;
			}
		});

	}

}
